import request from "../utils/request";
export function injectXHR() {
    let XMLHttpRequest = window.XMLHttpRequest;
    let oldOpen = XMLHttpRequest.prototype.open;
    let oldSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method,url,async) {
        if(!url.match(/logs/) && !url.match(/cityjson/)){
            this.logData = { method, url, async };
        }
        return oldOpen.apply(this, arguments);
    }

    XMLHttpRequest.prototype.send = function(body) {
        if(this.logData) {
            let startTime = Date.now();
            let handler = (type) => (event) =>{
                let duration = Date.now() - startTime,
                    status = this.status,
                    statusText = this.statusText;
                request.send({
                    kind: 'stability',
                    type: 'xhr',
                    eventType: type,
                    pathName: this.logData.url,
                    method: this.logData.method,
                    params: body ?? '',
                    status: `${status}-${statusText}`,
                    duration,
                    response: this.responseText ?? ''
                })
            }

            ['load', 'error', 'abort'].forEach(type =>{
                this.addEventListener(type,handler(type),false);
            })
        }
        return oldSend.apply(this, arguments);
    }
}